package com.zhonggong.emp.activemq;


import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;


import com.zhonggong.empConsumer.service.ConsumerManager;
import com.zhonggong.empConsumer.service.impl.ConsumerManagerImpl;

public class EmpConsumer {
	private String userName = "root";
	private String password = "root";
	private String brokerURL = "tcp://0.0.0.0:61616";
	private ConnectionFactory factory;
	private Connection connection;
	private Session session;
	private Destination destination;
	private MessageConsumer consumer;
	public ConsumerManager consumerManager = new ConsumerManagerImpl();
	public void start() {
		try {
			factory = new ActiveMQConnectionFactory(userName, password, brokerURL);
			connection = factory.createConnection();
			connection.start();
			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			destination = session.createQueue("computers");
			consumer = session.createConsumer(destination);
			// 实现一个消息的监听器
			consumer.setMessageListener(new MessageListener() {
				public void onMessage(Message message) {
					try {
						System.out.println("1111");
						String text = ((TextMessage) message).getText();
						consumerManager.writefile("D:\\test.txt", text);
						System.out.println(text);
						System.out.println("2222");
					} catch (JMSException e) {
						e.printStackTrace();
					}
				}
			});
			consumer.close();
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
}
